//
//  HomeVC+ViewAction.swift
//  WatermarkCamera
//
//  Created by 赵新 on 5/7/2024.
//

import UIKit
import AxcBedrock
import RxSwift

extension HomeVC {
    /// 视图事件
    func viewActionBind() {
        navgationAction()
        centerViewAction()
        footerViewAction()
        bottomViewAction()
    }

    fileprivate func navgationAction() {
        // 点击设置的菜单
        headerView.menuBtn.axc.addEvent { [weak self] btn in
            guard let weakSelf = self else { return }
            weakSelf.headerMenuAnimation()
        }
        // 菜单内操作
        // --点击画幅调整
        menuView.aspectRatioBtn.actionBlock = { [weak self] btn in
            guard let weakSelf = self else { return }
            weakSelf.menuView.aspectRatioBtn.aspectRatio = btn.aspectRatio

            AxcDevice.PlayVibration(.heavy)
            weakSelf.setAspectRatio(btn.aspectRatio)
            weakSelf.autoFrame()
            weakSelf.photoAspectRatio = btn.aspectRatio // 记录拍照模式下使用的画幅比
            UserDefaults.standard.set(btn.aspectRatio.rawValue, forKey: "Camera_AspectRatio")
        }

        // 点击意见反馈
        headerView.feedBackBtn.axc.addEvent { [weak self] _ in
            // 调用优化之后的h5页面
            guard let weakSelf = self else { return }
            weakSelf.stopCamera()
            let vm = FeedbackVM()
            vm.parameters = nil
            vm.questionType = .None
            vm.path = FeedbackVM.Html5Path.feedback
            let vc = FeedbackVC(vm)
            weakSelf.navigationController?.pushViewController(vc, animated: true)
        }
        
        // 点击滤镜
        headerView.filterBtn.axc.addEvent {
            [weak self] _ in
            guard let self = self else { return }
            self.setFilterView(shown: true)
        }
        
        // 点击滤镜View的关闭按钮
        filterView.closeAction.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            self.setFilterView(shown: false)
        }).disposed(by: rx.disposeBag)
        
        // 点击滤镜View的对比按钮
        filterView.contrastAction.subscribe(onNext: {
            [weak self] event in
            guard let self = self else { return }
            switch event {
            case .down: // 按下
                self.cameraView?.removeAllFilter()
            case .up: // 抬起
                self.addFilter()
            }
        }).disposed(by: rx.disposeBag)
        // 选中某个滤镜效果
        filterView.didSelecteFilterItem.subscribe(onNext: {
            [weak self] filterItem in
            guard let self = self else { return }
            // 更新滤镜数据源,刷新页面
            self.vm.didSelected(filterItem: filterItem)
            self.filterView.reloadData()
            // 添加滤镜
            self.addFilter()
            // 存储滤镜的名字
            self.vm.saveFilter(name: filterItem.name)
        }).disposed(by: rx.disposeBag)

        // --点击延迟拍照
        menuView.delayBtn.actionBlock = { [weak self] btn in
            guard let weakSelf = self else { return }
            weakSelf.menuView.delayBtn.delayTime = btn.delayTime
        }

        // --点击联系我们
        menuView.contactBtn.axc.addEvent { [weak self] _ in
            // 调用优化之后的h5页面
            guard let weakSelf = self else { return }
            weakSelf.stopCamera()
            let vm = FeedbackVM()
            vm.parameters = nil
            vm.questionType = .None
            vm.path = FeedbackVM.Html5Path.feedback
            let vc = FeedbackVC(vm)
            weakSelf.navigationController?.pushViewController(vc, animated: true)
        }

        // --点击相机设置
        menuView.cameraSettingBtn.axc.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            let vm = CameraSettingVM()
            let vc = CameraSettingVC(vm)
            weakSelf.navigationController?.pushViewController(vc, animated: true)
        }

        // -- 点击视频清晰度
        menuView.articulationBtn.actionBlock = { [weak self] btn in
            guard let weakSelf = self else { return }
            weakSelf.menuView.articulationBtn.articulation = btn.articulation

            AxcDevice.PlayShake(.heavy)
            weakSelf.cameraView?.setWriterArticulation(btn.articulation)
//            switch btn.articulation {
//            case ._1080p:
//                let alert = AlertView()
//                alert.title = "1080P同步时，会特别耗时及耗费流量"
//                alert.msg = "同步视频，建议切换回720P或540P模式"
//                alert.style = .confirm(title: "我知道了")
//                alert.show()
//            default: break
//            }
            UserDefaults.standard.set(btn.articulation.rawValue, forKey: "Camera_VideoArticulation")
        }
        
        // 选择焦距倍数
        focusAdjustView.didSelectedFocusScale.subscribe(onNext: {
            [weak self] scale in
            guard let self = self else { return }
            self.controlView.setCameraZoomFactor(scale: scale)
        }).disposed(by: rx.disposeBag)
        
        // 将要缩放改变焦距
        controlView.willChangeFocus.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            self.focusAdjustView.showRuleView()
        }).disposed(by: rx.disposeBag)
        
        // 焦距倍数变化
        controlView.focusZoomScaleChanged.subscribe(onNext: {
            [weak self] scale in
            guard let self = self else { return }
            self.focusAdjustView.set(scale: scale, isShowScales: true)
        }).disposed(by: rx.disposeBag)
        
        // 已经结束缩放改变焦距
        controlView.didEndChangeFocus.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            self.focusAdjustView.hideRuleView(delay: true)
        }).disposed(by: rx.disposeBag)

    }
    
    fileprivate func centerViewAction() {
        // 控制视图被操作时
        controlView.hitTestBlock = { [weak self] in
            guard let self = self else { return }
            // 隐藏滤镜view
            self.setFilterView(shown: false)
        }
    }
    

    fileprivate func footerViewAction() {
        // 点击水印选择按钮
        footerView.watermarkBtn.axc.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.showWatermarkAlertView()
        }

        // ---水印选择
        watermarkSelectView.didSelectWatermarkBlock = { [weak self] _, wmModel in
            guard let weakSelf = self else { return }
            weakSelf.vm.setWatermarkModel(wmModel)
        }

        // ---无水印选择
        watermarkSelectView.didSelectEmptyWatermarkBlock = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.vm.setWatermarkModel(nil)
        }

        // ---水印选择即将消失
        watermarkSelectView.willDismissBlock = { [weak self] in
            guard let weakSelf = self else { return }
            // 显示相机上水印
            weakSelf.watermarkContentView.isHidden = false
            weakSelf.controlView.isHidden = false
        }

        // ---水印选择需要消失
        watermarkSelectView.dismissBlock = { [weak self] in
            guard let weakSelf = self else { return }
            // 显示相机上水印
            weakSelf.watermarkContentView.isHidden = false
            weakSelf.controlView.isHidden = false
        }

        // 水印加载完成
        watermarkSelectView.watermarkListLoadCompletion = { [weak self] list in
            guard let weakSelf = self else { return }
//            weakSelf.vm.setWatermarkModel(list.first)
        }

        // 底部视图被操作时
        footerView.hitTestBlock = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.headerMenuShow(false)
            // 隐藏滤镜view
            weakSelf.setFilterView(shown: false)
        }

        // 点击本地相册
        footerView.localAlbumBtn.axc.addEvent { [weak self] btn in
            guard let weakSelf = self else { return }
            weakSelf.clickLocalAlbumBtn()
        }

        // 点击拍照
        footerView.actionBtn.axc.addEvent { [weak self] btn in
            guard let weakSelf = self else { return }
            weakSelf.clickTakePhoto()
        }

        // 点击录制/停止按钮
        footerView.videoActionBtn.axc.addEvent { [weak self] btn in
            let cameraStatus = AuthorizedManager.camera()
            let microphoneStatus = AuthorizedManager.microphone()
            let photoAlbumStatus = AuthorizedManager.photoAlbum()
            guard let weakSelf = self else { return }
            if cameraStatus.info.isAvailable { // 有权限
                if microphoneStatus.info.isAvailable { // 有权限
                    if photoAlbumStatus.info.isAvailable { // 有权限
                        btn.isUserInteractionEnabled = false
                        AxcDevice.PlayShake(.threeDimensionalTouch_pop)
                        switch weakSelf.vm.videoRecordState {
                        case .stop: // 当处于停止状态下，点击按钮，则开始录制
                            weakSelf.startRecording()
                        case .pause: // 当处于暂停状态下，点击按钮，则继续录制
                            weakSelf.stopRecording(breakOffType: .none)
                        case .being: // 当处于进行中时，点击按钮，则停止录制
                            weakSelf.stopRecording(breakOffType: .none)
                        }

                        btn.axc.delayLast(1) { [weak btn] in
                            guard let weakBtn = btn else { return }
                            weakBtn.isUserInteractionEnabled = true
                        }
                    } else { // 无权限
                        AuthorizedManager.showPrivacyAlert(type: .photoAlbum)
                    }
                } else {
                    if microphoneStatus == .notDetermined { // 尚未选择
                        AuthorizedManager.microphoneRequest()
                    } else {
                        AuthorizedManager.showPrivacyAlert(type: .microphone)
                    }
                }
            } else {
                AuthorizedManager.showPrivacyAlert(type: .camera)
            }
        }

        // 点击暂停/继续录制按钮
        footerView.pauseVideoRecordBtn.actionBlock = { [weak self] btn in
            guard let weakSelf = self else { return }
            AxcDevice.PlayShake(.medium)
            switch btn.recordState {
            case .pause: // 点下暂停
                weakSelf.pauseRecording()
            case .continue: // 点下继续
                weakSelf.continueRecording()
            }
        }

        // 点击翻转
        footerView.flipBtn.axc.addEvent { [weak self] btn in
            guard let weakSelf = self else { return }
            weakSelf.clickFlip()
        }
    }

    fileprivate func bottomViewAction() {
        // 点击照片
        modeView.clickPhotoBlock = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.switchFunctionMode(.photo)
        }

        // 点击视频
        modeView.clickVideoBlock = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.switchFunctionMode(.video)
        }

        // 选中功能列表中第一个可选的
        modeView.selectFirstAction()
    }

    func switchFunctionMode(_ functionModel: HomeModeView.Mode) {
        // 重置焦距
        resetCameraFocusScale()
        focusAdjustView.hideRuleView()
        
        switch functionModel {
        case .photo:
            photoMode()
            /// 要切换回拍照的画幅比
            if let photoAspectRatio = photoAspectRatio {
                setAspectRatio(photoAspectRatio, animated: true)
                autoFrame()
            }
        case .video:
            videoMode()
        }
    }
    
    /// 隐藏/显示滤镜View
    func setFilterView(shown: Bool) {
        filterView.setHidden(!shown)
    }
    
    /// 添加滤镜
    func addFilter() {
        cameraView?.removeAllFilter()
        guard let filter = vm.selectedFilterItem?.filter else { return }
        cameraView?.appendFilter(filter)
    }
    
}
